package com.example.easybuy.service;

import com.example.easybuy.entity.*;
import com.example.easybuy.mapper.*;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class DataSyncService {
    
    @Autowired
    private NewsMapper newsMapper;
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    
    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private ProductCategoryMapper productCategoryMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private UserAddressMapper userAddressMapper;
    
    @Autowired
    private ResultMapper resultMapper;
    
    @Autowired
    private RestHighLevelClient elasticsearchClient;
    
    public void syncData() {
        try {
            // 同步News表
            syncNews();
            
            // 同步Order表
            syncOrders();
            
            // 同步OrderDetail表
            syncOrderDetails();
            
            // 同步Product表
            syncProducts();
            
            // 同步ProductCategory表
            syncProductCategories();
            
            // 同步User表
            syncUsers();
            
            // 同步UserAddress表
            syncUserAddresses();
            
            // 同步Result表
            syncResults();
            
            System.out.println("所有数据同步完成");
        } catch (IOException e) {
            System.err.println("数据同步失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private void syncNews() throws IOException {
        List<News> newsList = newsMapper.findAll();
        BulkRequest bulkRequest = new BulkRequest();
        
        for (News news : newsList) {
            String json = "{\"id\":\"" + news.getId() + "\",\"title\":\"" + news.getTitle() + "\",\"content\":\"" + news.getContent() + "\",\"createTime\":\"" + news.getCreateTime() + "\"}";
            IndexRequest indexRequest = new IndexRequest("news");
            indexRequest.id(String.valueOf(news.getId()));
            indexRequest.source(json, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        
        elasticsearchClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("News数据同步完成，共同步 " + newsList.size() + " 条数据");
    }
    
    private void syncOrders() throws IOException {
        List<Order> orderList = orderMapper.findAll();
        BulkRequest bulkRequest = new BulkRequest();
        
        for (Order order : orderList) {
            String json = "{\"id\":\"" + order.getId() + "\",\"userId\":\"" + order.getUserId() + "\",\"loginName\":\"" + order.getLoginName() + "\",\"userAddress\":\"" + order.getUserAddress() + "\",\"createTime\":\"" + order.getCreateTime() + "\",\"cost\":\"" + order.getCost() + "\",\"serialNumber\":\"" + order.getSerialNumber() + "\"}";
            IndexRequest indexRequest = new IndexRequest("orders");
            indexRequest.id(String.valueOf(order.getId()));
            indexRequest.source(json, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        
        elasticsearchClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("Order数据同步完成，共同步 " + orderList.size() + " 条数据");
    }
    
    private void syncOrderDetails() throws IOException {
        List<OrderDetail> orderDetailList = orderDetailMapper.findAll();
        BulkRequest bulkRequest = new BulkRequest();
        
        for (OrderDetail orderDetail : orderDetailList) {
            String json = "{\"id\":\"" + orderDetail.getId() + "\",\"orderId\":\"" + orderDetail.getOrderId() + "\",\"productId\":\"" + orderDetail.getProductId() + "\",\"quantity\":\"" + orderDetail.getQuantity() + "\",\"cost\":\"" + orderDetail.getCost() + "\"}";
            IndexRequest indexRequest = new IndexRequest("order_details");
            indexRequest.id(String.valueOf(orderDetail.getId()));
            indexRequest.source(json, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        
        elasticsearchClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("OrderDetail数据同步完成，共同步 " + orderDetailList.size() + " 条数据");
    }
    
    private void syncProducts() throws IOException {
        List<Product> productList = productMapper.findAll();
        BulkRequest bulkRequest = new BulkRequest();
        
        for (Product product : productList) {
            String json = "{\"id\":\"" + product.getId() + "\",\"name\":\"" + product.getName() + "\",\"description\":\"" + product.getDescription() + "\",\"price\":\"" + product.getPrice() + "\",\"stock\":\"" + product.getStock() + "\",\"categoryLevel1Id\":\"" + product.getCategoryLevel1Id() + "\",\"categoryLevel2Id\":\"" + product.getCategoryLevel2Id() + "\",\"categoryLevel3Id\":\"" + product.getCategoryLevel3Id() + "\",\"fileName\":\"" + product.getFileName() + "\",\"isDelete\":\"" + product.getIsDelete() + "\"}";
            IndexRequest indexRequest = new IndexRequest("products");
            indexRequest.id(String.valueOf(product.getId()));
            indexRequest.source(json, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        
        elasticsearchClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("Product数据同步完成，共同步 " + productList.size() + " 条数据");
    }
    
    private void syncProductCategories() throws IOException {
        List<ProductCategory> productCategoryList = productCategoryMapper.findAll();
        BulkRequest bulkRequest = new BulkRequest();
        
        for (ProductCategory productCategory : productCategoryList) {
            String json = "{\"id\":\"" + productCategory.getId() + "\",\"name\":\"" + productCategory.getName() + "\",\"parentId\":\"" + productCategory.getParentId() + "\",\"type\":\"" + productCategory.getType() + "\",\"iconClass\":\"" + productCategory.getIconClass() + "\"}";
            IndexRequest indexRequest = new IndexRequest("product_categories");
            indexRequest.id(String.valueOf(productCategory.getId()));
            indexRequest.source(json, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        
        elasticsearchClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("ProductCategory数据同步完成，共同步 " + productCategoryList.size() + " 条数据");
    }
    
    private void syncUsers() throws IOException {
        List<User> userList = userMapper.findAll();
        BulkRequest bulkRequest = new BulkRequest();
        
        for (User user : userList) {
            String json = "{\"id\":\"" + user.getId() + "\",\"loginName\":\"" + user.getLoginName() + "\",\"userName\":\"" + user.getUserName() + "\",\"password\":\"" + user.getPassword() + "\",\"sex\":\"" + user.getSex() + "\",\"identityCode\":\"" + user.getIdentityCode() + "\",\"email\":\"" + user.getEmail() + "\",\"mobile\":\"" + user.getMobile() + "\",\"type\":\"" + user.getType() + "\"}";
            IndexRequest indexRequest = new IndexRequest("users");
            indexRequest.id(String.valueOf(user.getId()));
            indexRequest.source(json, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        
        elasticsearchClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("User数据同步完成，共同步 " + userList.size() + " 条数据");
    }
    
    private void syncUserAddresses() throws IOException {
        List<UserAddress> userAddressList = userAddressMapper.findAll();
        BulkRequest bulkRequest = new BulkRequest();
        
        for (UserAddress userAddress : userAddressList) {
            String json = "{\"id\":\"" + userAddress.getId() + "\",\"userId\":\"" + userAddress.getUserId() + "\",\"address\":\"" + userAddress.getAddress() + "\",\"createTime\":\"" + userAddress.getCreateTime() + "\",\"isDefault\":\"" + userAddress.getIsDefault() + "\",\"remark\":\"" + userAddress.getRemark() + "\"}";
            IndexRequest indexRequest = new IndexRequest("user_addresses");
            indexRequest.id(String.valueOf(userAddress.getId()));
            indexRequest.source(json, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        
        elasticsearchClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("UserAddress数据同步完成，共同步 " + userAddressList.size() + " 条数据");
    }
    
    private void syncResults() throws IOException {
        List<Result> resultList = resultMapper.findAll();
        BulkRequest bulkRequest = new BulkRequest();
        
        for (Result result : resultList) {
            String json = "{\"stuno\":\"" + result.getStuno() + "\",\"subjectName\":\"" + result.getSubjectName() + "\",\"score\":\"" + result.getScore() + "\",\"age\":\"" + result.getAge() + "\"}";
            IndexRequest indexRequest = new IndexRequest("results");
            indexRequest.id(String.valueOf(result.getStuno()));
            indexRequest.source(json, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        
        elasticsearchClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("Result数据同步完成，共同步 " + resultList.size() + " 条数据");
    }
}